/**
 * Created by JetBrains WebStorm.
 * User: denysk
 * Date: 6/11/11
 * Time: 11:20 PM
 * To change this template use File | Settings | File Templates.
 */
Namespace("sketch.ui");

(function(fwk, ui, $){
    ui.ActionDesigner = klass(null, {
        _constructor: function(domSelector, commands){
            this.domSelector = domSelector;
            this.commands = commands;
        },

        clear: function(){
            $(this.domSelector).empty();
        },

        update: function(actionBag){
            this.clear();

            var element = $(this.domSelector);

            var group;
            var that = this;

            actionBag.iterate(function(groupName){
                group = $(document.createElement("div")).attr("id", "action_" + groupName).addClass("action-group");
                var description = $(document.createElement("div")).text(groupName);
                element.append(group.append(description));
            }, function(commandConstructor, commandImage){
                that._updateActionEditor(group, commandConstructor, commandImage);
            });
        },

        _updateActionEditor: function(group, commandConstructor, commandImage){
            var templateCommand = commandConstructor();
            var elementId = group.attr("id") + "_" + templateCommand.name();
            var editor = $("#actionEditor-image");
            var shortcut = ui.keyboard.getShortcutKey(templateCommand);
            var description = shortcut != null
                ? templateCommand.description() + " (" + shortcut + ")"
                : templateCommand.description();

            var container = $(document.createElement("div")).attr("id", elementId).addClass("action");
            group.append(container);

            var mediator = {
                commandManager: fwk.commandManager,
                executeCommand: function(){
                    var command = commandConstructor();
                    fwk.commandManager.execute(command);
                }
            };

            container.data("mediator", mediator);

            editor.tmpl({
                        controlId: elementId + "_input",
                        mediatorHolder: elementId,
                        image: commandImage,
                        description: description
                    })
                    .appendTo(container);

            var initFunction = editor.data("init");
            if (!initFunction) {
                throw {name: "InvalidOperationException", message: "The editor must have an init function in its dictionary"};
            }
            initFunction();
        }
    });
})(sketch.framework, sketch.ui, jQuery);